<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="960px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="110px"
      v-loading="formLoading"
      class="max-h-70vh"
    >
      <el-scrollbar height="65vh">
        <el-card shadow="never" class="mb-20px">
          <template #header>
            <span>基础信息</span>
          </template>
          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="姓名" prop="name">
                <el-input v-model="formData.name" placeholder="请输入姓名" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别" prop="sex">
                <el-input v-model="formData.sex" placeholder="请输入性别" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出生年月" prop="dateOfBirth">
                <el-date-picker
                  v-model="formData.dateOfBirth"
                  type="date"
                   value-format="x"
                  placeholder="请选择出生年月"
                  class="w-full"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="民族" prop="nation">
                <el-input v-model="formData.nation" placeholder="请输入民族" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="学历" prop="education">
                <el-input v-model="formData.education" placeholder="请输入学历" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="毕业院校" prop="graduateInstitutions">
                <el-input v-model="formData.graduateInstitutions" placeholder="请输入毕业院校" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="专业" prop="major">
                <el-input v-model="formData.major" placeholder="请输入专业" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="身高(cm)" prop="height">
                <el-input-number
                  v-model="formData.height"
                  :min="0"
                  :max="300"
                  :precision="1"
                  class="w-full"
                  placeholder="请输入身高"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="健康状况" prop="healthCondition">
                <el-input v-model="formData.healthCondition" placeholder="请输入健康状况" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="婚姻状况" prop="marriageState">
                <el-input v-model="formData.marriageState" placeholder="请输入婚姻状况" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <el-card shadow="never" class="mb-20px">
          <template #header>
            <span>面试信息</span>
          </template>
          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="应聘岗位" prop="post">
                <el-cascader
                  v-model="formData.post"
                  :options="postOptions"
                  :props="postProps"
                  :show-all-levels="false"
                  clearable
                  filterable
                  class="w-full"
                  placeholder="请选择应聘岗位"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="应聘渠道" prop="channels">
                <el-input v-model="formData.channels" placeholder="请输入应聘渠道" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="邀约人" prop="inviter">
                <CascaderUser v-model="formData.inviter" class="w-full" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="面试时间" prop="interviewTime">
                <el-date-picker
                  v-model="formData.interviewTime"
                  type="datetime"
                  value-format="x"
                  placeholder="请选择面试时间"
                  class="w-full"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="到面日期" prop="date">
                <el-date-picker
                  v-model="formData.date"
                  type="date"
                   value-format="x"
                  placeholder="请选择到面日期"
                  class="w-full"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="跟进结果" prop="trailResult">
                <el-input
                  v-model="formData.trailResult"
                  type="textarea"
                  :rows="2"
                  placeholder="请输入跟进结果"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="面试结果" prop="interviewResult">
                <el-input v-model="formData.interviewResult" placeholder="请输入面试结果" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态" prop="status">
                <el-select v-model="formData.status" placeholder="请选择状态" class="w-full">
                  <el-option
                    v-for="item in statusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="初试官" prop="preliminaryUser">
                <el-input v-model="formData.preliminaryUser" placeholder="请输入初试官" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="复试官" prop="reexamineUser">
                <el-input v-model="formData.reexamineUser" placeholder="请输入复试官" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否录用" prop="whetherToHire">
                <el-input v-model="formData.whetherToHire" placeholder="请输入是否录用" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="不录用原因" prop="noHireCause">
                <el-input
                  v-model="formData.noHireCause"
                  type="textarea"
                  :rows="2"
                  placeholder="请输入不录用原因"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="约定入职日期" prop="agreeDate">
                <el-date-picker
                  v-model="formData.agreeDate"
                  type="datetime"
                  value-format="x"
                  placeholder="请选择约定入职日期"
                  class="w-full"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <el-card shadow="never" class="mb-20px">
          <template #header>
            <span>联系方式</span>
          </template>
          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="手机" prop="urgentPhone">
                <el-input v-model="formData.urgentPhone" placeholder="请输入手机号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="身份证号" prop="cardId">
                <el-input v-model="formData.cardId" placeholder="请输入身份证号" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="政治面貌" prop="politicalOutlook">
                <el-input v-model="formData.politicalOutlook" placeholder="请输入政治面貌" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="现住地址" prop="currentAddress">
                <el-input
                  v-model="formData.currentAddress"
                  type="textarea"
                  :rows="2"
                  placeholder="请输入现住地址"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="户籍地址" prop="address">
                <el-input
                  v-model="formData.address"
                  type="textarea"
                  :rows="2"
                  placeholder="请输入户籍地址"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="紧急联系人" prop="emergencyContact">
                <el-input v-model="formData.emergencyContact" placeholder="请输入紧急联系人" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="关系" prop="relation">
                <el-input v-model="formData.relation" placeholder="请输入关系" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系人电话" prop="emergencyContactPhone">
                <el-input v-model="formData.emergencyContactPhone" placeholder="请输入联系人电话" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="上一份薪资" prop="lastSalary">
                <el-input v-model="formData.lastSalary" placeholder="请输入上一份薪资" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="期望薪资" prop="expectedSalary">
                <el-input v-model="formData.expectedSalary" placeholder="请输入期望薪资" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="可到岗时间" prop="arrivalTime">
                <el-input v-model="formData.arrivalTime" placeholder="请输入可到岗时间" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="离开原因" prop="leaveCause">
                <el-input
                  v-model="formData.leaveCause"
                  type="textarea"
                  :rows="2"
                  placeholder="请输入离开原因"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input
                  v-model="formData.remark"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入备注"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <el-card shadow="never" class="mb-20px">
          <template #header>
            <div class="flex items-center justify-between">
              <span>学习经历</span>
              <el-button type="primary" text @click="addStudyRow">新增</el-button>
            </div>
          </template>
          <el-table :data="formData.studyList" border size="small">
            <el-table-column label="开始时间" width="160">
              <template #default="{ row }">
                <el-date-picker
                  v-model="row.startDate"
                  type="date"
                   value-format="x"
                  placeholder="开始时间"
                />
              </template>
            </el-table-column>
            <el-table-column label="结束时间" width="160">
              <template #default="{ row }">
                <el-date-picker
                  v-model="row.endDate"
                  type="date"
                   value-format="x"
                  placeholder="结束时间 / 至今"
                />
              </template>
            </el-table-column>
            <el-table-column label="学校" min-width="160">
              <template #default="{ row }">
                <el-input v-model="row.school" placeholder="请输入学校" />
              </template>
            </el-table-column>
            <el-table-column label="专业" min-width="160">
              <template #default="{ row }">
                <el-input v-model="row.major" placeholder="请输入专业" />
              </template>
            </el-table-column>
            <el-table-column label="荣誉/职务" min-width="160">
              <template #default="{ row }">
                <el-input v-model="row.post" placeholder="请输入荣誉或职务" />
              </template>
            </el-table-column>
            <el-table-column label="是否毕业" width="140">
              <template #default="{ row }">
                <el-input v-model="row.graduation" placeholder="请输入是否毕业" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="90" fixed="right">
              <template #default="{ $index }">
                <el-button type="danger" text @click="removeStudyRow($index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <el-card shadow="never" class="mb-20px">
          <template #header>
            <div class="flex items-center justify-between">
              <span>工作经历</span>
              <el-button type="primary" text @click="addWorkRow">新增</el-button>
            </div>
          </template>
          <el-table :data="formData.workList" border size="small">
            <el-table-column label="开始时间" width="160">
              <template #default="{ row }">
                <el-date-picker
                  v-model="row.startDate"
                  type="date"
                   value-format="x"
                  placeholder="开始时间"
                />
              </template>
            </el-table-column>
            <el-table-column label="结束时间" width="160">
              <template #default="{ row }">
                <el-date-picker
                  v-model="row.endDate"
                  type="date"
                   value-format="x"
                  placeholder="结束时间 / 至今"
                />
              </template>
            </el-table-column>
            <el-table-column label="工作单位" min-width="180">
              <template #default="{ row }">
                <el-input v-model="row.company" placeholder="请输入工作单位" />
              </template>
            </el-table-column>
            <el-table-column label="岗位/职务" min-width="160">
              <template #default="{ row }">
                <el-input v-model="row.post" placeholder="请输入岗位或职务" />
              </template>
            </el-table-column>
            <el-table-column label="证明人" min-width="140">
              <template #default="{ row }">
                <el-input v-model="row.certifier" placeholder="请输入证明人" />
              </template>
            </el-table-column>
            <el-table-column label="联系方式" min-width="140">
              <template #default="{ row }">
                <el-input v-model="row.phone" placeholder="请输入联系方式" />
              </template>
            </el-table-column>
            <el-table-column label="工作内容" min-width="200">
              <template #default="{ row }">
                <el-input v-model="row.description" placeholder="请输入工作内容" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="90" fixed="right">
              <template #default="{ $index }">
                <el-button type="danger" text @click="removeWorkRow($index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <el-card shadow="never">
          <template #header>
            <div class="flex items-center justify-between">
              <span>家庭成员</span>
              <el-button type="primary" text @click="addFamilyRow">新增</el-button>
            </div>
          </template>
          <el-table :data="formData.familyList" border size="small">
            <el-table-column label="姓名" min-width="140">
              <template #default="{ row }">
                <el-input v-model="row.name" placeholder="请输入姓名" />
              </template>
            </el-table-column>
            <el-table-column label="关系" min-width="140">
              <template #default="{ row }">
                <el-input v-model="row.relation" placeholder="请输入关系" />
              </template>
            </el-table-column>
            <el-table-column label="年龄" width="120">
              <template #default="{ row }">
                <el-input v-model="row.age" placeholder="请输入年龄" />
              </template>
            </el-table-column>
            <el-table-column label="工作单位" min-width="180">
              <template #default="{ row }">
                <el-input v-model="row.company" placeholder="请输入工作单位" />
              </template>
            </el-table-column>
            <el-table-column label="岗位" min-width="160">
              <template #default="{ row }">
                <el-input v-model="row.post" placeholder="请输入岗位" />
              </template>
            </el-table-column>
            <el-table-column label="联系方式" min-width="160">
              <template #default="{ row }">
                <el-input v-model="row.phone" placeholder="请输入联系方式" />
              </template>
            </el-table-column>
            <el-table-column label="备注" min-width="200">
              <template #default="{ row }">
                <el-input v-model="row.remark" placeholder="请输入备注" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="90" fixed="right">
              <template #default="{ $index }">
                <el-button type="danger" text @click="removeFamilyRow($index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-scrollbar>
    </el-form>
    <template #footer>
      <el-button type="primary" :disabled="formLoading" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { toRaw } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import {
  RecruitInterviewApi,
  type RecruitInterview,
  type RecruitInterviewFamilyItem,
  type RecruitInterviewStudyItem,
  type RecruitInterviewWorkItem
} from '@/api/business/hr/recruit/interview'
import { RecruitPostApi, type RecruitPost } from '@/api/business/hr/recruit/post'
import { INTERVIEW_STATUS_OPTIONS } from '@/views/business/hr/recruit/constants'
import { handleTree } from '@/utils/tree'

interface RecruitInterviewFormModel
  extends Omit<RecruitInterview, 'studyList' | 'workList' | 'familyList'> {
  studyList: RecruitInterviewStudyItem[]
  workList: RecruitInterviewWorkItem[]
  familyList: RecruitInterviewFamilyItem[]
}

interface RecruitPostCascaderNode extends RecruitPost {
  value: string
  label: string
  isLeaf?: boolean
  children?: RecruitPostCascaderNode[]
}

const { t } = useI18n()
const message = useMessage()

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formType = ref<'create' | 'update'>('create')
const formLoading = ref(false)
const formRef = ref<FormInstance>()

const statusOptions = INTERVIEW_STATUS_OPTIONS

const postOptions = ref<RecruitPostCascaderNode[]>([])
const postProps = {
  value: 'post',
  label: 'post',
  emitPath: false,
  checkStrictly: true
}

const getDefaultForm = (): RecruitInterviewFormModel => ({
  id: undefined,
  interviewTime: undefined,
  trailResult: undefined,
  interviewResult: undefined,
  post: undefined,
  channels: undefined,
  inviter: undefined,
  date: undefined,
  name: undefined,
  sex: undefined,
  dateOfBirth: undefined,
  nation: undefined,
  education: undefined,
  graduateInstitutions: undefined,
  major: undefined,
  height: undefined,
  healthCondition: undefined,
  marriageState: undefined,
  cardId: undefined,
  urgentPhone: undefined,
  politicalOutlook: undefined,
  currentAddress: undefined,
  address: undefined,
  emergencyContact: undefined,
  relation: undefined,
  emergencyContactPhone: undefined,
  leaveCause: undefined,
  lastSalary: undefined,
  expectedSalary: undefined,
  arrivalTime: undefined,
  preliminaryUser: undefined,
  reexamineUser: undefined,
  whetherToHire: undefined,
  noHireCause: undefined,
  agreeDate: undefined,
  remark: undefined,
  status: undefined,
  userId: undefined,
  dingUserId: undefined,
  studyList: [],
  workList: [],
  familyList: []
})

const formData = reactive<RecruitInterviewFormModel>(getDefaultForm())

const formRules: FormRules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  post: [{ required: true, message: '请选择应聘岗位', trigger: 'change' }],
  inviter: [{ required: true, message: '请选择邀约人', trigger: 'change' }],
  interviewTime: [{ required: true, message: '请选择面试时间', trigger: 'change' }],
  urgentPhone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

const resetForm = () => {
  Object.assign(formData, getDefaultForm())
  formRef.value?.clearValidate()
}

const parseList = (raw?: string | null) => {
  if (!raw) {
    return []
  }
  try {
    const parsed = JSON.parse(raw)
    return Array.isArray(parsed) ? (parsed as T[]) : []
  } catch {
    return []
  }
}

const loadPostOptions = async () => {
  try {
    const data = await RecruitPostApi.getRecruitPostList({})
    const tree = handleTree(data || [], 'id', 'parentId') as RecruitPostCascaderNode[]
    const markLeaf = (nodes: RecruitPostCascaderNode[]) => {
      nodes.forEach((node) => {
        node.value = node.post || `${node.id}`
        node.label = node.post || node.dept || '-'
        if (node.children && node.children.length > 0) {
          markLeaf(node.children as RecruitPostCascaderNode[])
          node.isLeaf = false
        } else {
          node.isLeaf = true
        }
      })
      return nodes
    }
    postOptions.value = markLeaf(tree)
  } catch (error) {
    console.warn('招聘岗位获取失败', error)
  }
}

const open = async (type: 'create' | 'update', id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = type === 'create' ? t('action.create') : t('action.update')
  formType.value = type
  resetForm()
  if (postOptions.value.length === 0) {
    await loadPostOptions()
  }
  if (id) {
    formLoading.value = true
    try {
      const data = await RecruitInterviewApi.getRecruitInterview(id)
      Object.assign(formData, {
        ...getDefaultForm(),
        ...data,
        studyList: parseList<RecruitInterviewStudyItem>(data.studyList),
        workList: parseList<RecruitInterviewWorkItem>(data.workList),
        familyList: parseList<RecruitInterviewFamilyItem>(data.familyList)
      })
    } finally {
      formLoading.value = false
    }
  }
}

const addStudyRow = () => {
  formData.studyList.push({
    startDate: undefined,
    endDate: undefined,
    school: '',
    major: '',
    post: '',
    graduation: ''
  })
}

const removeStudyRow = (index: number) => {
  formData.studyList.splice(index, 1)
}

const addWorkRow = () => {
  formData.workList.push({
    startDate: undefined,
    endDate: undefined,
    company: '',
    post: '',
    certifier: '',
    phone: '',
    description: ''
  })
}

const removeWorkRow = (index: number) => {
  formData.workList.splice(index, 1)
}

const addFamilyRow = () => {
  formData.familyList.push({
    name: '',
    relation: '',
    age: '',
    company: '',
    post: '',
    phone: '',
    remark: ''
  })
}

const removeFamilyRow = (index: number) => {
  formData.familyList.splice(index, 1)
}

const emit = defineEmits(['success'])

const submitForm = async () => {
  if (!formRef.value) return
  await formRef.value.validate()
  formLoading.value = true
  try {
    const raw = toRaw(formData)
    const { studyList, workList, familyList, ...rest } = raw
    const payload: RecruitInterview = {
      ...rest,
      studyList: JSON.stringify(studyList ?? []),
      workList: JSON.stringify(workList ?? []),
      familyList: JSON.stringify(familyList ?? [])
    }
    if (formType.value === 'create') {
      await RecruitInterviewApi.createRecruitInterview(payload)
      message.success(t('common.createSuccess'))
    } else {
      await RecruitInterviewApi.updateRecruitInterview(payload)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

defineExpose({ open })
</script>
